package com.hd.pzhwlxt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hd.pzhwlxt.mapper.GoodsMapper;
import com.hd.pzhwlxt.mapper.GoodsPurchaseMapper;
import com.hd.pzhwlxt.pojo.GoodsPrice;
import com.hd.pzhwlxt.pojo.GoodsPurchase;
import com.hd.pzhwlxt.service.GoodsPriceService;
import com.hd.pzhwlxt.service.GoodsPurchaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;

/**
 * @create: 2022-09-26 10:54
 * @author: 怀念天空
 * @Description:
 */

@Service
public class GoodsPurchaseServiceImpl extends ServiceImpl<GoodsPurchaseMapper, GoodsPurchase> implements GoodsPurchaseService {

    @Autowired
    private GoodsPurchaseMapper goodsPurchaseMapper;

    @Autowired
    private GoodsMapper goodsMapper;


    @Autowired
    private GoodsPriceService goodsPriceService;

    @Override
    public List<GoodsPurchase> getAllPurchaseInfo() {
        return goodsPurchaseMapper.getAllPurchaseInfo();
    }

    @Override
    public Page<GoodsPurchase> getAllPurchaseInfoPage(Page<Object> page) {
        return goodsPurchaseMapper.getAllPurchaseInfoPage(page);
    }

    @Override
    public boolean addPurchaseInfo(GoodsPurchase goodsPurchase) {
        Integer goodsId = goodsPurchase.getGoodsId();
        QueryWrapper<GoodsPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsId);
        GoodsPrice goodsPrice = goodsPriceService.getOne(wrapper);
        Double inPrice = goodsPrice.getInPrice();
        goodsPurchase.setMoney(BigDecimal.valueOf(inPrice * goodsPurchase.getPurchaseNum()));
        return goodsPurchaseMapper.insert(goodsPurchase) > 0;
    }

    @Override
    public boolean updatePurchaseInfo(GoodsPurchase goodsPurchase) {
        Integer goodsId = goodsPurchase.getGoodsId();
        QueryWrapper<GoodsPrice> wrapper = new QueryWrapper<>();
        wrapper.eq("goods_id", goodsId);
        GoodsPrice goodsPrice = goodsPriceService.getOne(wrapper);
        goodsPrice.setStock(goodsPrice.getStock() + goodsPurchase.getPurchaseNum());
        goodsPriceService.updateById(goodsPrice);
        goodsPurchase.setStatus(1);
        return goodsPurchaseMapper.updateById(goodsPurchase) > 0;
    }
}
